<?php
namespace App\Http\Controllers\Api;

use App\Helper\Utils\TimeUtil;
use App\V3\V3_1\Models\DispatchBillDriverModel;
use App\V3\V3_1\Models\DispatchBillGoodsDetailModel;
use App\V3\V3_1\Models\DispatchBillModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 发货单
 * Class DispatchBillController
 * @package App\Http\Controllers\Api
 */
class DispatchBillController extends BaseController
{
    /**
     * 发货单列表
     * change 在 2021/11/8 10:37 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //查询
        if($this->getUserId()==$this->getMainUserId()){
            $model = DispatchBillModel::where(['main_id'=>$this->getMainUserId()])
                ->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
                ->toArray();
        }else{
            $model = DispatchBillModel::where(['main_id'=>$this->getMainUserId(),'user_id'=>$this->getUserId()])
                ->orderBy('id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
                ->toArray();
        }
        if($model['data']){
            foreach ($model['data'] as &$value){
                $value['goods_info'] = DispatchBillGoodsDetailModel::where('dispatch_bill_id',$value['id'])->get();
                $value['driver'] =  DispatchBillDriverModel::where('dispatch_bill_id',$value['id'])->first();
            }
        }
        return $this->success($model);
    }

    /**
     * 详情
     * change 在 2021/11/8 10:44 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = DispatchBillModel::find($data['id']);
        if($model){
            $model['goods_info'] = DispatchBillGoodsDetailModel::where('dispatch_bill_id',$model['id'])->get();
            $model['driver'] = DispatchBillDriverModel::where('dispatch_bill_id',$model['id'])->first();
        }
        return $this->success($model);
    }

    /**
     * 添加发货单
     * change 在 2021/11/8 10:44 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'consignee' =>'required|string',//收货人
            'phone' =>'required|string',//收货人联系电话
            'address' =>'required|string',//收货地址
            'deliver_time' =>'required|string',//发货时间
            'deliver_person' =>'required|string',//发货人
            'deliver_phone' =>'required|string',//发货人联系方式
            'deliver_addr' =>'required|string',//发货地址
            'remark' =>'string',//备注
            'transport_type' =>'integer',//运输方式：1-空运 2-海运 3-铁路 4-公路
            'total_piece' =>'integer',//商品总件数
            'goods_info' =>'string',//商品信息  array
//            'driver' =>'string',//司机信息 array
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = $data;
            if(isset($data['goods_info']) && !empty($data['goods_info'])) unset($mainInfo['goods_info']);
//            if(isset($data['driver']) && empty($data['driver'])) unset($mainInfo['driver']);
            $mainInfo['main_id'] = $this->getMainUserId();
            $mainInfo['user_id'] = $this->getUserId();
            $mainInfo['created_at'] = time();
            $mainInfo['deliver_time'] = strtotime($data['deliver_time']);
            $mainInfo['order_no'] = 'F'. $this->getMainUserId().TimeUtil::getMillisecond();//订单号
            //创建销售主单信息
//            print_r($mainInfo);die;
            $mainId = DispatchBillModel::insertGetId($mainInfo);
            //商品详细添加
            if(isset($data['goods_info']) && !empty($data['goods_info'])){
                $goodsInfo = json_decode($data['goods_info'],true);
                foreach ($goodsInfo as &$value){
                    $value['main_id'] = $this->getMainUserId();
                    $value['dispatch_bill_id'] = $mainId;
                    $value['created_at'] = time();
                }
                DispatchBillGoodsDetailModel::insert($goodsInfo);
            }
//            //司机添加
//            if(isset($mainInfo['driver']) && !empty($mainInfo['driver'])){
//                $newDriver = json_decode($mainInfo['driver'],true);
//                $newDriver['dispatch_bill_id'] = $mainId;
//                $newDriver['main_id'] = $this->getMainUserId();
//                SellDriverModel::insert($newDriver);
//            }
            DB::commit();//提交事务
            return $this->success($mainId);
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加销售单');
        }
    }

    /**
     * 编辑发货单
     * change 在 2021/11/8 13:58 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//发货单主键id
            'consignee' =>'string',//收货人
            'phone' =>'string',//收货人联系电话
            'address' =>'string',//收货地址
            'deliver_time' =>'string',//发货时间
            'deliver_person' =>'string',//发货人
            'deliver_phone' =>'string',//发货人联系方式
            'deliver_addr' =>'string',//发货地址
            'remark' =>'string',//备注
            'goods_info' =>'string',//商品信息  json array
            'driver' =>'string',//司机信息  json array
            'transport_type' =>'integer',//运输方式：1-空运 2-海运 3-铁路 4-公路
            'total_piece' =>'integer',//商品总件数
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            //报溢报损主单
            $mainInfo = $data;
            if(isset($mainInfo['deliver_time'])) $mainInfo['deliver_time'] = strtotime($data['deliver_time']);
            //商品详细添加
            if(isset($mainInfo['goods_info']) && !empty($mainInfo['goods_info'])){
                $goodsInfo = json_decode($data['goods_info'],true);
                foreach ($goodsInfo as $value){//更新商品信息
                    //更新
                    if(isset($value['id'])){
                        DispatchBillGoodsDetailModel::where(['id'=>$value['id']])->update($value);
                    }else{//添加
                        $value['main_id'] = $this->getMainUserId();
                        $value['dispatch_bill_id'] = $data['id'];
                        $value['created_at'] = time();
                        DispatchBillGoodsDetailModel::insert($value);
                    }
                }
                unset($mainInfo['goods_info']);
            }
            //司机更新添加
            if(isset($mainInfo['driver']) && !empty($mainInfo['driver'])){
                $driver = DispatchBillDriverModel::where('dispatch_bill_id',$data['id'])->first();
                if($driver){
                    DispatchBillDriverModel::where('dispatch_bill_id',$data['id'])->update(json_decode($mainInfo['driver'],true));
                }else{
                    $newDriver = json_decode($mainInfo['driver'],true);
                    $newDriver['dispatch_bill_id'] = $data['id'];
                    $newDriver['main_id'] = $this->getMainUserId();
                    $newDriver['created_at'] = time();
                    DispatchBillDriverModel::insert($newDriver);
                }
                unset($mainInfo['driver']);
            }
            //更新销售单
            DispatchBillModel::where('id',$data['id'])->update($mainInfo);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加销售单');
        }
    }

    /**
     * 删除发货单
     * change 在 2021/11/8 11:30 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//发货单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = DispatchBillModel::find($data['id']);
        $model->delete();
        $this->log('删除发货单',$model);
        return $this->success();
    }

    /**
     *  绑定司机(添加编辑)
     * change 在 2021/11/8 11:30 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindDriver(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'dispatch_bill_id' =>'required|integer',//发货单主键id
            'plate_number' =>'required|string',//车牌
            'name' =>'required|string',//司机姓名
            'phone' =>'required|string',//提货司机电话
            'logistics_company' =>'required|string',//物流公司
            'remark' =>'string',//备注
            'plate_image' =>'string',//车牌照片
            'id_card_image' =>'string',//身份证照片
            'driving_licence' =>'string',//驾驶证照片
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $model = DispatchBillDriverModel::where('dispatch_bill_id',$data['dispatch_bill_id'])->first();
        if($model){
            DispatchBillDriverModel::where('dispatch_bill_id',$data['dispatch_bill_id'])->update($data);
        }else{
            $data['created_at'] = time();
            DispatchBillDriverModel::insert($data);
        }
        return $this->success();
    }
}
